<?php
namespace app\common\helper;
/**
 * 加密解密助手
 *
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/19 0019
 * Time: 17:08
 */
class Encrypt {

    /**
     * 解密
     * @param string $str 要解密的字符
     * @param string $secret_key 用于解密的密钥
     * @return bool|mixed|string
     */
    public static function decode($str, $secret_key) {
        return self::crypt($str, "D", $secret_key);
    }

    /**
     * 加密
     * @param string $str 要加密的字符
     * @param string $secret_key 用于加密的密钥
     * @return bool|mixed|string
     */
    public static function encode($str, $secret_key) {
        return self::crypt($str, "E", $secret_key);
    }

    /**
     * 加解密算法
     *
     * @param $string
     * @param $operation
     * @param string $key
     * @return bool|mixed|string
     */
    private static  function crypt($string,$operation,$key=''){
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }
}